package com.itheima.server.controller;

import com.itheima.domain.UserInfo;
import com.itheima.server.interceptor.UserHolder;
import com.itheima.server.service.UserInfoService;
import com.itheima.server.service.UserService;
import com.itheima.vo.UserInfoVo;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/users")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;


    @Resource
    private UserService userService;


    /**
     * 查询用户基本信息
     * @param token
     * @param userID
     * @return
     */
    @GetMapping
    public ResponseEntity<UserInfoVo> userInfo(@RequestHeader("Authorization") String token,Long userID){
        Long id = UserHolder.getUserId();
        if (userID == null){
            userID = id;
        }
        UserInfoVo userInfoVo = userInfoService.getById(userID);
        return ResponseEntity.ok(userInfoVo);
    }

    @PutMapping
    public ResponseEntity<String> updateUserInfo(@RequestBody UserInfo userInfo,@RequestHeader("Authorization") String token){
        //获取userId
        Long id = UserHolder.getUserId();
        userInfo.setId(id);
        userInfoService.updateUserInfo(userInfo);
        return  ResponseEntity.ok("OK");
    }


    /**
     * 修改手机号
     * 1、发送验证阿门
     * @return
     */
    @PostMapping("/phone/sendVerificationCode")
    public ResponseEntity<String> sendVerificationCode(){
        String mobile = UserHolder.getMobile();
        //直接去发验证码
        userService.sendMsg(mobile);
        return ResponseEntity.ok("OK");
    }

    /**
     * 修改手机号
     * 2、校验验证码
     * @return
     */
    @PostMapping("/phone/checkVerificationCode")
    public ResponseEntity<Map> checkVerificationCode(@RequestBody Map<String,String> map){
        Boolean verification = userService.checkVerificationCode(map.get("verificationCode"));
        Map<String,Boolean> res  = new HashMap<>();
        res.put("verification",verification);
        return ResponseEntity.ok(res);
    }

    /**
     * 修改手机号
     * 3、保存
     * @return
     */
    @PostMapping("/phone")
    public ResponseEntity<String> phone(@RequestBody Map<String,String> map){
        userService.updatePhone(map.get("phone"));
        return ResponseEntity.ok("OK");
    }


}
